<template>
  <div class="upload_file_shop">
    <ul class="el-upload-list el-upload-list--picture-card" v-if="paramsType === 2">
      <li tabindex="0" class="el-upload-list__item is-success" v-for="(image, index) in image_list">
        <el-image :src="image" class="el-upload-list__item-thumbnail" fit="cover"></el-image>
        >
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="previewImage(image)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span class="el-upload-list__item-delete" @click="deleteImage(index)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </li>
      <el-upload
        :action="action" :data="QiniuData"
        :show-file-list="false"
        :on-error="uploadError"
        :on-success="uploadSuccess"
        :before-upload="beforeAvatarUpload"
        :accept="accept"
        class="avatar-uploader"
        style="display: inline-block"
        v-if=" image_list == [] || image_list.length<limitNum"
      >
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <el-dialog :visible.sync="isPreviewImageShow" :modal="false">
        <el-image width="100%" :src="previewImageUrl" alt=""></el-image>
      </el-dialog>
    </ul>
    <ul class="el-upload-list el-upload-list--picture-card" v-if="paramsType === 1">
      <li tabindex="0" class="el-upload-list__item is-success" v-if="isUrlAvailable">
        <el-image :src="image_item" class="el-upload-list__item-thumbnail" fit="cover"></el-image>
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="previewImage(image_item)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span class="el-upload-list__item-delete" @click="deleteImage(-1, image_item)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </li>
      <el-upload
        :action="action"
        :data="QiniuData"
        :show-file-list="false"
        :on-error="uploadError"
        :on-success="uploadSuccess"
        :before-upload="beforeAvatarUpload"
        :accept="accept"
        class="avatar-uploader"
        style="display: inline-block"
        v-if="!image_item"
      >
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <el-dialog :visible.sync="isPreviewImageShow" :modal="false">
        <img width="100%" :src="previewImageUrl" alt="">
      </el-dialog>
    </ul>
  </div>
</template>

<script>
  export default {
    name: "Upload",
    components: {},
    props: {
      image_list: { //图片list
        type: Array,
        default: () => []
      },
      image_item: { // 单个图片地址
        type: String,
        default: ''
      },
      limitNum: { // 默认上传图片最大数量
        type: Number,
        default: 5
      },
      paramsType: { // 传参种类: 1表示字符串, 2表示数组
        type: Number,
        default: 0
      },
      accept:{
        type:String,
        default:'.jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF'
      }
    },
    data() {
      return {
        action: "https://up.qiniup.com", // 七牛云的上传地址（华东区）
        qiniuaddr: "http://twst.isart.me/", // 七牛云的图片外链地址
        QiniuData: {
          key: "", //图片名字处理
          token: "" //七牛云token
        },
        isPreviewImageShow: false, //是否显示预览
        previewImageUrl: '' //图片预览地址
      };
    },
    computed: {
      isUrlAvailable () {
        if (this.image_item == '' || this.image_item === null) {
          return false
        } else {
          return true
        }
      },
    },
    methods: {

      /**
       * @author HongWei ZHu
       * @date 2020/6/21
       * @Description: 上传文件成功
       * @param response {{obj}} 上传文件成功结果
       **/
      uploadSuccess(response) {
        if (this.paramsType == 2) {
          this.image_list.push(`${this.qiniuaddr}/${response.key}`)
          this.$emit('uploadSuccess', this.image_list)
        } else if (this.paramsType == 1) {
          let newUrl = `${this.qiniuaddr}/${response.key}`
          this.$emit('uploadSuccess', newUrl)
        }
        this.loading.close()
      },
      /**
       * @author HongWei Zhu
       * @date 2020/6/21
       * @Description:
       **/
      uploadError() {
        this.$message({
          message: "上传出错，请重试！",
          type: "error",
          center: true
        });
        this.loading.close()
      },
      /**
       * @author HongWei Zhu
       * @date 2020/6/21
       * @Description: 上传文件检测
       * @param file {{String}} 文件名
       **/
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return
        }
        let file_old = file.name;
        let file_name  = file_old.split(".")[1];
        let timestamp = Date.parse(new Date());
        let result = timestamp + '.' + file_name;
        this.QiniuData.key = `upload_pic_${result}`;
        this.loading = this.$loading({
          lock: true,
          text: '上传图片中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      },
      /**
       * @author HongWei Zhu
       * @date 2020/6/21
       * @Description: 删除图片
       * @param index
       *          Type Number, 删除图片index, -1表示删除内容不是数组
       *        url
       *          Type String, 删除单个图片
       **/
      deleteImage(index, url) {
        if (index == -1) {
          this.$emit('deleteImage')
        } else {
          this.image_list.splice(index, 1)
          this.$emit('deleteImage', this.image_list)
        }
      },
      /**
       * @Description: 大图预览
       * @author HongWei Zhu
       * @date 2020/6/21
       * @param {{string}} 展示图片地址
       */
      previewImage(url) {
        this.previewImageUrl = url
        this.isPreviewImageShow = true
      },
      getQiniuToken() {
        window._api.commonGetQiniuToken().then(res => {
          this.QiniuData.token = res.data
        })
      },
    },
    mounted() {
      this.getQiniuToken();
    },
  }
</script>

<style>
  .upload_file_shop {
    width: 80%;
    white-space: nowrap;
    overflow: auto;
    margin-top: 20px;
  }


  .avatar-uploader .el-upload {
    display: inline-block !important;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin: 0 8px 8px 0;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 146px;
    height: 146px;
    line-height: 146px;
    text-align: center;
  }

  .avatar {
    width: 146px;
    height: 146px;
    display: block;
  }

</style>
